<?php
if(!defined('MID_APP')) exit('No direct script access allowed');

/**
 * ---------------------------------------------
 * 全局公共函数库
 * ---------------------------------------------
 * @author  Midnight,  yangyunzhou@foxmail.com
 * ---------------------------------------------
 * @copyright  Midnight Studio
 * ---------------------------------------------
 */

/**
 * 加载Jquery
 *
 * @param String $file 文件
 * @param String $dir 目录
 */
function js($file, $dir) {
	// 如果存在目录视为加载插件
	if(!empty($dir)) $dir = $dir . '/';
	$x = ROOT . 'js/' . $dir . $file;
	return $x;
}

// 获取上传目录
function get_upload_dir($file) {
	return ROOT.'upload/'.$file;
}

/**
 * --------------------------------------------
 * 路由模式url生成
 * --------------------------------------------
 * @author  Midnight,  yangyunzhou@foxmail.com
 * @param $yl 路由
 * @param $cs 参数, 支持数组
 */
function url($yl,$cs) {
	$qz = $url = false;
	$hz = C('URL_HTML_SUFFIX');
	// url 模式
	if(C('URL_MODEL') != 2) $qz = 'index.php/';
	// url 扩展名
	if($hz) {
		if($yl && !$cs) $url = $yl . $hz;
		else $url = $yl . '-' . $cs . $hz;
	}
	return $qz . $url;
}

/**
 * ------------------------------------
 * 日期格式化, 分析时间返回时间戳
 * ------------------------------------
 * @author  Midnight(杨云洲),  yangyunzhou@foxmail.com
 * @param $time 要分析的日期
 * @return Int
 */
function dateFormat($time) {
	if(!empty($time)) {
		Import('Org.Util.Date');
		return Date::parse($time) + (8 * 3600); // 修复格式化后丢失时区BUG
	}
}

/**
 * ----------------------------
 * 转义时间
 * ----------------------------
 * @author Midnight(杨云洲) yangyunzhou@foxmail.com
 * @param Int $time 时间戳, 为空自动获取当前时间
 * @param Srting $gs 格式, 默认精确获取到分钟
 */
function togmdate($time = false,$gs = 'Y-m-d H:i') {
	return gmdate($gs,getTime($time));
}

/**
 * ----------------------
 * 返回时间戳
 * ----------------------
 * @author Midnight(杨云洲) yangyunzhou@foxmail.com
 * @return Int Unix时间戳, 并加上中国时区
 */
function getTime($time = false) {
	return ($time) ? $time : time() + (8 * 3600);
}

/**
 * -----------------------
 * 输出时间, 年月日格式
 * -----------------------
 * @author Midnight(杨云洲) yangyunzhou@foxmail.com
 * @param Int 时间戳
 */
function showDate($time = false) {
	$time = ($time) ? getTime($time) : getTime();
	$data = gmdate('Y',$time) . '年';
	$data .= gmdate('m',$time) . '月';
	$data .= gmdate('d',$time) . '日 ';
	$data .= gmdate('H:i',$time);
	return $data;
}

/**
 * ------------------------------------
 * 操作 DataTemp 缓存表
 *
 * 支持写入与读取, 读取自动缓存数据
 * 写入自动将值序列化, 读取自动反序列化
 * ------------------------------------
 * @author  Midnight(杨云洲),  yangyunzhou@foxmail.com
 * @param String $key
 * @param String $value
 */
function dataTemp($key = false,$value = false) {
	if(empty($key)) return false;
	if(!empty($value)) {
		$db = M('DataTemp');
		$value = serialize($value);
		$verify = $db->where("`key`='$key'")->find();
		if($verify) $io = $db->execute("UPDATE `__TABLE__` SET `value`='{$value}' WHERE (`key`='{$key}') LIMIT 1");
		else $db->execute("INSERT INTO `__TABLE__` (`key` ,`value`)VALUES ('{$key}', '{$value}')");
		F($key,$value);
		unset($db,$key,$value);
		return $io;
	} else {
		$indexSlide = F($key);
		if(empty($indexSlide)) {
			$db = M('DataTemp');
			$io = $db->where("`key`='{$key}'")->find();
			F($key,$io['value']);
			$re = unserialize($io['value']);
			unset($db,$io,$key);
		} else {
			$re = unserialize($indexSlide);
			unset($db,$indexSlide,$key);
		}
		return $re;
	}
}

/**
 * -------------------------------
 * 获取 Select Option
 * -------------------------------
 * @author Midnight(杨云洲) yangyunzhou@foxmail.com
 * @param Array $_arr 选项数据集
 * @param Array $_s 选项参数, 留空为处理一维数组
 * @param Int $_id 要选中的选项
 * @return Array
 */
function getSelect($_arr,$_s,$_id) {
	foreach($_arr as $k=>$v) {
		if(is_array($_s)) {
			$k = $v[$_s[0]];
			$v = $v[$_s[1]];
		}
		if($_id == $k) $io .= '<option value="' . $k . '" selected="selected">' . $v . '</option>';
		else $io .= '<option value="' . $k . '">' . $v . '</option>';
	}
	unset($_arr,$_s,$_id,$k,$v);
	return $io;
}

/**
 * ------------------------------------
 * 获取 Radio, 支持选中
 * ------------------------------------
 * @author  Midnight(杨云洲),  yangyunzhou@foxmail.com
 * @param $_arr 数据集
 * @param $_s 元素名称
 * @param $_id 选中的ID
 *
 * 使用方法:
 * getRadio(array(1=>'开放', 0=>'关闭'), 'site_switch', $io['site_switch']);
 */
function getRadio($_arr = array(),$_s,$_id = FALSE,$class = 'radio') {
	if(empty($_arr)) return FALSE;
	$io = '';
	foreach($_arr as $k=>$v) {
		if($k == $_id) $io .= '<input type="radio" name="' . $_s . '" id="' . $_s . $k . '" class="' . $class . '" value="' . $k . '" checked="checked" /><label for="' . $_s . $k . '" class="' . $class . '">' . $v . "</label>";
		else $io .= '<input type="radio" name="' . $_s . '" id="' . $_s . $k . '" class="' . $class . '" value="' . $k . '" /><label for="' . $_s . $k . '" class="' . $class . '">' . $v . "</label>";
	}
	unset($_arr,$_s,$_id,$v);
	return $io;
}

/**
 * ----------------------------
 * 获取 多选框, 支持选中
 * ----------------------------
 * @author  Midnight(杨云洲),  yangyunzhou@foxmail.com
 * @param Array $_arr 数据集
 * @param Array $_s 键值格式
 * @param Array $_id 需选中的ID
 * @return Array
 */
function getCheckbox($_arr = array(),$_s = array(),$_id = array()) {
	$_id = (!empty($_id)) ? explode(',',$_id) : false;
	foreach($_arr as $_a) {
		if(in_array($_a[$_s[0]],$_id)) {
			$re = '<input name="' . $_s['names'] . '" type="checkbox" value="' . $_a[$_s['value']] . '" checked="checked" /> ' . "&nbsp;" . $_a[$_s['name']];
			$re .= '<input type="hidden" name="hidden_' . $_s['names'] . '" value="' . $_a[$_s['value']] . '" />';
			$io[] = $re;
		} else {
			$io[] = '<input name="' . $_s['names'] . '" type="checkbox" value="' . $_a[$_s['value']] . '" /> ' . "&nbsp;" . $_a[$_s['name']];
		}
	}
	unset($_arr,$_s,$_id,$_a);
	return $io;
}

/**
 * ------------------------------------
 * 获取 多选框, 仅支持单框选中
 * ------------------------------------
 * @author  Midnight(杨云洲),  yangyunzhou@foxmail.com
 * @param $show
 * @param $name
 * @param $select
 * @return String
 *
 * 使用方法:
 * getCheckboxSingle('允许人们发表新文章的评论(全局)', 'globalComment', 0);
 */
function getCheckboxSingle($show,$name,$select) {
	if($select == true) {
		$io = '<input type="checkbox" name="' . $name . '" id="' . $name . '" value="1" checked="checked" /><label for="' . $name . '">' . $show . '</label>';
	} else {
		$io = '<input type="checkbox" name="' . $name . '" id="' . $name . '"  value="1" /><label for="' . $name . '">' . $show . '</label>';
	}
	return $io;
}

/**
 * Get either a Gravatar URL or complete image tag for a specified email address.
 *
 * @param string $email The email address
 * @param string $s Size in pixels, defaults to 80px [ 1 - 512 ]
 * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
 * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
 * @param boole $img True to return a complete IMG tag False for just the URL
 * @param array $atts Optional, additional key/value attributes to include in the IMG tag
 * @return String containing either just a URL or a complete image tag
 * @source http://gravatar.com/site/implement/images/php/
 */
function get_gravatar($email,$s = 80,$d = 'mm',$r = 'g',$img = false,$atts = array()) {
	$url = 'http://www.gravatar.com/avatar/';
	$url .= md5(strtolower(trim($email)));
	$url .= "?s=$s&d=$d&r=$r";
	if(!$url) {
		$url = 'http://www.somewhere.com/homestar.jpg';
	}
	if($img) {
		$url = '<img src="' . $url . '"';
		foreach($atts as $key=>$val) {
			$url .= ' ' . $key . '="' . $val . '"';
		}
		$url .= ' />';
	}
	return $url;
}